<template>
  <div>
    <el-button type="primary" @click="showUploadDialog">添加新线路</el-button>
    <input type="text" name="search" v-model="searchKeyword" class="search-input">
    <el-button @click="searchLogistics" size="mini">搜索</el-button>
    <el-button @click="backToList" v-model="searching" :disabled="!searching"  size="mini">返回</el-button>

    <el-dialog v-model="uploadDialogVisible" title="添加/编辑线路">
      <form class="upload-container" enctype="multipart/form-data" method="POST">
        线路名称<input type="text" name="name" v-model="formData.name" :disabled="editMode"><br />
        途径<input type="text" name="pathBy" v-model="formData.pathBy"><br />
        地址<input type="text" name="address" v-model="formData.address"><br />
        电话<input type="text" name="phone" v-model="formData.phone"><br />
        <el-button v-if="!editMode" type="primary" @click="addLogistics" :disabled="!formData.name || !formData.pathBy || !formData.address || !formData.phone">上传</el-button>
        <el-button v-if="editMode" type="primary" @click="updateLogistics" :disabled="!formData.pathBy || !formData.address || !formData.phone">保存</el-button>
      </form>
    </el-dialog>

    <el-table :data="logisticsList" :border="true">
      <el-table-column label="线路名称" prop="name"></el-table-column>
      <el-table-column label="途径" prop="pathBy"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <el-table-column label="电话" prop="phone"></el-table-column>
      <el-table-column>
        <template #default="{row}">
          <!-- <el-button size="mini" @click="toggleTop(row)">{{ topLogistics.includes(row) ? '取消置顶' : '置顶' }}</el-button> -->
          <!-- <el-button size="mini" @click="setTop(row)">置顶</el-button> -->
          <el-button @click="topLine(row)">{{row.onTop==0? '置顶' : '取消置顶'}}</el-button>
          <el-button size="mini" @click="editLogistics(row)">编辑</el-button>
          <el-button @click="handleDelete(row)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'LogisticsManagement',
  setup() {
    const logisticsList = ref([]);
    const currentPage = ref(1);
    const pageSize = 10;
    const total = ref(0);
    const uploadDialogVisible = ref(false);
    const searching = ref(false);
    const formData = ref({
      name: '',
      pathBy: '',
      address: '',
      phone: ''
    });
    const editMode = ref(false);
    const editRow = ref(null);
    const searchKeyword = ref('');
    const filteredLogisticsList = ref([]);
    const topLogistics = ref([]);
    const token = localStorage.getItem('token');
    

    const showUploadDialog = () => {
      uploadDialogVisible.value = true;
      editMode.value = false;
      formData.value = {
        name: '',
        pathBy: '',
        address: '',
        phone: ''
      };
    };

    const editLogistics = (row) => {
      uploadDialogVisible.value = true;
      editMode.value = true;
      editRow.value = row;
      formData.value = {
        name: row.name,
        pathBy: row.pathBy,
        address: row.address,
        phone: row.phone
      };
    };
     
    //获取物流路线列表
    const getLogisticsList = async () => {
    try {
      const response = await axios.get('./getLogisticsList', {
        headers: {
          'Authorization': `Bearer ${token}`,
        }
      });
      logisticsList.value = response.data.logisticsList;
    } catch (error) {
        console.error(error);
        ElMessage.error('获取物流路线列表失败');
      }
    }

    //添加新物流路线
    const addLogistics = async () => {
      try {
        const response = await axios.post('./addLogistics', formData.value, {
          headers: {
            'Authorization': `Bearer ${token}`,
          }
        });
        ElMessage.success(response.data.message);
        getLogisticsList();
        uploadDialogVisible.value = false;
      } catch (error) {
        console.error(error);
        ElMessage.error('添加新物流路线失败');
        // window.location.reload();
      }
    }

    //编辑物流路线
    const updateLogistics = async () => {
      try {
        const response = await axios.put('./updateLogistics', formData.value, {
          headers: {
            'Authorization': `Bearer ${token}`,
          }
        });
        ElMessage.success(response.data.message);
        getLogisticsList();
        uploadDialogVisible.value = false;
      } catch (error) {
        console.error(error);
        ElMessage.error('更新物流路线失败');
      }
    }

    //删除物流路线
    const handleDelete = async (row) => {
      try {
        const response = await axios.delete('./delLogistics', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
          params: {
            name: row.name
          }
        });
        if (response.data.success) {
          ElMessage.success(response.data.message);
          getLogisticsList();
        } else {
          ElMessage.error(response.data.message);
          window.location.reload();
        }
      } catch (error) {
        console.error(error);
        ElMessage.error(error);
      }
    };

    //搜索物流路线
    const searchLogistics = async () => {
      console.log(searchKeyword)
      if (searchKeyword.value.trim() !== '') {
        logisticsList.value = logisticsList.value.filter(item => item.name.toLowerCase().includes(searchKeyword.value.trim().toLowerCase()));
        searching.value = true;
      }
      else {
        ElMessage.error('未查询到该物流路线');
      }
    };

    //返回物流路线列表
    const backToList = () => {
      searchKeyword.value = '';
      searching.value = false;
      getLogisticsList();
    };

    //置顶
    const topLine = async (row) => {
      const id = {id: row.id};
      const response = await axios.put('./topLine', id);
      if(response.data.success) ElMessage.success(response.data);
      else ElMessage.error(response.data);
      window.location.reload();
      // getLogisticsList();
    };


    // const setTop = (row) => {
    //   if (!topLogistics.value.includes(row)) {
    //     logisticsList.value.splice(logisticsList.value.indexOf(row), 1);
    //     topLogistics.value.unshift(row);
    //   }
    // };

    // const removeTop = (row) => {
    //   if (topLogistics.value.includes(row)) {
    //     topLogistics.value.splice(topLogistics.value.indexOf(row), 1);
    //     logisticsList.value.push(row);
    //   }
    // };

    // const toggleTop = (row) => {
    //   if (topLogistics.value.includes(row)) {
    //     removeTop(row);
    //   } else {
    //     setTop(row);
    //   }
    // };


    //！！！！！！！！！！！首选
    // const setTop = (row) => {
    //   const index = logisticsList.value.indexOf(row);
    //   logisticsList.value.splice(index, 1);
    //   logisticsList.value.unshift(row);
    //   const button = document.querySelector('.el-table__body-wrapper .el-table__body .el-button');
    //   button.innerText = '取消置顶';
    //   button.onclick = () => removeTop(row); 
    // };

    // const removeTop = (row) => {
    //   const index = logisticsList.value.indexOf(row);
    //   logisticsList.value.splice(index, 1);
    //   logisticsList.value.push(row);
    //   const button = document.querySelector('.el-table__body-wrapper .el-table__body .el-button');
    //   button.innerText = '置顶';
    //   button.onclick = () => setTop(row); 
    // };

    const handleCurrentChange = (val) => {
          currentPage.value = val;
          getLogisticsList();
    };


    onMounted(() => {
      getLogisticsList();
    });

    return {
      logisticsList,
      getLogisticsList,
      addLogistics,
      updateLogistics,
      handleDelete,
      showUploadDialog,
      uploadDialogVisible,
      formData,
      pageSize,
      currentPage,
      total,
      handleCurrentChange,
      editMode,
      topLine,
      editRow,
      editLogistics,
      searchLogistics,
      backToList,
      searchKeyword,
      filteredLogisticsList,
      searching,
      // setTop,
      // removeTop,
      topLogistics,
      // toggleTop
    }
  }
}
</script>

<style>
.logistics-container {
  padding: 20px;
}

.top-section {
  margin-bottom: 20px;
}

.logistics-list table {
  width: 100%;
}

.logistics-list th, .logistics-list td {
  padding: 5px 10px;
}

.delete-button {
  background-color: red;
  color: white;
}

.upload-container {
  padding: 20px;
  display: block;
}
</style>